﻿using Ekton_Manage_DomainCore.Aggregate;
using Ekton_Manage_Framework.Methods;
using Ekton_Manage_InfrastructureCore.SqlSugarHelper;
using Ekton_Manage_Mapper.EntityMappers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Ekton_Manage_Web.Filter
{
    public class ValidateModelFilter : ActionFilterAttribute
    {
        private readonly HttpGetUser _httpGetUser;
        private readonly SystemLogMapper _systemLog;
        private readonly SqlSugarMethod _sugarHelper;
        public ValidateModelFilter(HttpGetUser httpGetUser, SystemLogMapper systemLog, SqlSugarMethod sugarHelper)
        {
            _systemLog = systemLog;
            _httpGetUser = httpGetUser;
            _sugarHelper = sugarHelper;
        }

        public class ResultModel
        {
            public string msg { get; set; }
            public int code { get; set; }
            public List<FiledMesage> error { get; set; }
        }
        public class FiledMesage
        {
            public FiledMesage(string key, string message)
            {
                this.filed = key;
                this.details = message;
            }
            public string filed { get; set; }
            public string details { get; set; }
        }


        /// <summary>
        /// Action 调用前执行
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            //Save/Update 参数校验
            if (!actionContext.ModelState.IsValid)
            {
                //初始化返回结果
                var result = new ResultModel { msg = "参数错误", code = 400 };
                result.error = actionContext.ModelState.Keys
                .SelectMany(key => actionContext.ModelState[key].Errors.Select(x => new FiledMesage(key, x.ErrorMessage)))
                .ToList();
                result.error.ForEach((m) =>
                {
                    m.filed = m.filed.Replace("$.", string.Empty);
                });
                actionContext.Result = new JsonResult(result);
            }
            #region 日志记录
            var controllerActionDescriptor = actionContext.ActionDescriptor as ControllerActionDescriptor;
            var sys_log = new system_log
            {
                ip_address = _httpGetUser.GetClientIP().Result,
                oper_type = $"{actionContext.HttpContext.Request.Method}",
                oper_describe = $"ActionUrl:{controllerActionDescriptor.ControllerTypeInfo.FullName}.{controllerActionDescriptor.ActionName},Parame:{JsonConvert.SerializeObject(actionContext.ActionArguments)}",
                level = "Info",
                exception = string.Empty
            };
            Task.Run(() =>
            {
                if (actionContext.ModelState.IsValid)
                {
                    _sugarHelper.InsertData(sys_log);
                }
            });
            #endregion
        }

        /// <summary>
        /// Action 方法调用后，Result 方法调用前执行
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuted(ActionExecutedContext context)
        {

        }
    }
}
